package log

import (
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"time"
)

func InitLog(name string) {
	// 创建日志目录
	_ = os.Mkdir("logs", os.ModePerm)

	// fileWriter
	fileWriter, newFileWriterErr := rotatelogs.New(
		"./logs/signal-"+name+"-%Y%m%d.log",
		rotatelogs.WithMaxAge(time.Hour*24*30),
		rotatelogs.WithRotationTime(time.Hour*24),
	)
	if nil != newFileWriterErr {
		panic(newFileWriterErr)
	}

	// 日志格式
	encoder := zapcore.NewConsoleEncoder(zapcore.EncoderConfig{
		MessageKey:  "msg",
		LevelKey:    "level",
		TimeKey:     "time",
		CallerKey:   "file",
		EncodeLevel: zapcore.CapitalLevelEncoder,
		EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
			enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
		},
		EncodeCaller: zapcore.ShortCallerEncoder,
		EncodeDuration: func(d time.Duration, enc zapcore.PrimitiveArrayEncoder) {
			enc.AppendInt64(int64(d) / 1000000)
		},
	})

	// 日志等级
	infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl > zapcore.DebugLevel
	})

	core := zapcore.NewTee(
		zapcore.NewCore(encoder, zapcore.AddSync(fileWriter), infoLevel),
	)

	if len(os.Getenv("STD_LOG")) > 0 {
		core = zapcore.NewTee(
			zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), infoLevel),
		)
	}

	logger := zap.New(core, zap.AddCaller())
	zap.ReplaceGlobals(logger)

	zap.L().Info("||Signal(" + name + ")||")
}
